package com.tsmti.util;

import com.tsmti.core.common.constant.RedisConstants;
import com.tsmti.core.util.ConvertUtil;
import com.tsmti.core.util.RedisUtils;
import com.tsmti.core.util.SpringContextUtils;
import com.tsmti.system.entity.Organization;
import com.tsmti.system.service.OrganizationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package：com.tsmti.util
 * @Class：OrganzationUtil
 * @Description： 机构工具类
 * @Author：zcw
 * @Date：Created in 2018/5/15 18:24
 * @Company:
 * @Version：
 * @Modified By:
 */
public class OrganizationUtils {
    private static Logger logger = LoggerFactory.getLogger(OrganizationUtils.class);
    private static OrganizationService organizationService = SpringContextUtils.getBean(OrganizationService.class);


    /**
     *  根据编码获取名称
     * @param code
     * @return
     */
    public static String getNameByCode(String code) {
        Map<String,Organization> allMap = loadCache();
        String organizationName = "";
        if(allMap != null || allMap.size() > 0){
            Organization organization = allMap.get(code);
            if(organization != null ){
                organizationName = ConvertUtil.null2String(organization.getName());
            }
        }
        return organizationName;
    }

    /**
     *  根据编码获取对象
     * @param code
     * @return
     */
    public static Organization getValue(String code) {
        Map<String,Organization> allMap = loadCache();
        String organizationName = "";
        if(allMap != null || allMap.size() > 0){
            Organization organization = allMap.get(code);
            if(organization != null ){
                return organization;
            }
        }
        return null;
    }

    /**
     * 加载缓存
     */
    private static Map<String,Organization> loadCache(){
        Map<String,Organization> organizationMap = new HashMap<String,Organization>(16);
        try {
            organizationMap = (Map<String,Organization>) RedisUtils.getObject(RedisConstants.ORGANIZATION_CACHE);
            if(organizationMap == null){
                organizationMap = new HashMap<String,Organization>(16);
            }
        } catch (Exception e) {
            logger.warn("读取机构字典缓存失败!");
            e.printStackTrace();
        }
        if(organizationMap == null || organizationMap.size() <= 0){
            List<Organization> organizationList = organizationService.list();
            try {
                RedisUtils.setRedisToMap(RedisConstants.ORGANIZATION_CACHE,"code",organizationList);
            }catch (Exception e){
                logger.warn("加载机构缓存错误!",e);
            }
        }
        return organizationMap;
    }
}
